package org.arch_learn.zookeeper.zk_client_client_api;

import org.I0Itec.zkclient.IZkChildListener;
import org.I0Itec.zkclient.IZkDataListener;
import org.I0Itec.zkclient.ZkClient;

import java.util.List;

public class NodeOps {

    public static void main(String[] args) throws InterruptedException {
        //zkClient对原生zookeeper客户端api的封装，将异步会话创建同步化了。
        ZkClient zkClient = new ZkClient("127.0.0.1:2181");
        System.out.println("会话被创建了。。。");

        //获取节点的子节点
        List<String> children = zkClient.getChildren("/zk_client_persistent/zk_client_c1");
        System.out.println(children);

        //注册监听事件
        //客户端可以对一个不存在的节点进行子节点变更的监听的，只要该节点的子节点列表，或者该节点本身被创建或者删除都会触发监听
        zkClient.subscribeChildChanges("/zk_client_persistent_get", new IZkChildListener() {
            @Override
            public void handleChildChange(String parentPath, List<String> list) throws Exception {
                System.out.println(parentPath + "的子节点列表发生了变化，变化后的子节点列表为：" + list);
            }
        });

        //判断节点是否存在
        String path = "/zk_client_persistent_get";
        boolean exists = zkClient.exists(path);
        System.out.println("节点" + path + (exists ? "存在" : "不存在"));

        path = "/zk_client_persistent_get_aaa";
        exists = zkClient.exists(path);
        System.out.println("节点" + path + (exists ? "存在" : "不存在"));
        if (!exists) {
            zkClient.createEphemeral(path, "123");
        }
        exists = zkClient.exists(path);
        System.out.println("节点" + path + (exists ? "存在" : "不存在"));

        Object o = zkClient.readData(path);
        System.out.println(o);

        //注册监听
        zkClient.subscribeDataChanges(path, new IZkDataListener() {
            @Override
            public void handleDataChange(String path, Object o) throws Exception {
                System.out.println(path + "节点变化后的节点内容为：" + o);
            }

            @Override
            public void handleDataDeleted(String path) throws Exception {
                System.out.println(path + "节点被删除");
            }
        });
        //更新节点内容
        zkClient.writeData(path, "456");
        Thread.sleep(1000);
        zkClient.delete(path);
        Thread.sleep(1000);
    }
}
